import { IForm, IFormBusiness } from '@/modules/dao/BusinessDao';
import { IBusinessName, IBusinessStatus } from '@/modules/interface';
import useSyncState from '@/views/hooks/useSyncState';
import styled from '@emotion/styled';
import { Button, Select } from 'antd';
import dayjs from 'dayjs';
import { t } from 'i18next';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import CascaderSelect from './CascaderSelect';
import FormItem from './FormItem';

const { Option } = Select;

const FillFormContainer = styled.div`
	height: 100%;
	margin: 0 14px;
`;

const TitleContianer = styled.p`
	padding: 0 0 8px 0;
	margin: 0;
	font-weight: 400;
	font-size: 12px;
	color: #2a2a2a;
`;

const UserRole = styled.span`
	font-size: 12px;
	color: #666666;
	margin-bottom: 6px;
	display: ${(props: { userRole: string }) => (props.userRole === 'normal' ? 'none' : '')};
`;

const FormSelect = styled(Select)`
	width: 312px;
	height: 32px !important;
	.ant-select-selector {
		background: #f6f6f6 !important;
		border-radius: 4px !important;
		border: 0 !important;
	}
	.ant-select-selection-placeholder {
		line-height: 32px !important;
	}
	.ant-select-selection-item {
		line-height: 32px !important;
	}
	input {
		height: 32px !important;
	}
`;

interface FillFormProps {
	userRole: string;
	clentId: string;
	formData: IFormBusiness[];
}

interface SelectOption {
	id: string;
	value: string;
	label: string;
	clientId: string;
	status: IBusinessStatus;
	children: IForm[];
}

const filterFormDetail = (data: IFormBusiness[]) => {
	let forms: SelectOption[] = [];
	data.map(k => {
		if (k.forms.length > 0) {
			forms.push({
				id: k.forms[0].followId,
				value: k.forms[0].followId,
				label: dayjs(k.forms[0].createdAt || new Date()).format('YYYY-MM-DD HH:mm:ss'),
				clientId: k.clientId,
				status: k.status,
				children: k.forms.map(c => ({ ...c, value: c.detailId ? c.detailId : c.formName, label: c.formName, disabled: !c.detailId }))
			});
		}

		console.log(k, 'filterFormDetail');
	});

	return forms;
};

const FillForm = (props: FillFormProps) => {
	const { userRole, formData, clentId } = props;

	const handleChange = (value: any) => {
		const form = formList().find(item => item.formTemplate === value) || null;
		setSelected(value);
	};

	const [formList, setFormList] = useSyncState<{ followId: string; formId: string; formTemplate: string; formName: string; title: string; detailId: string }[]>([]);

	const [selected, setSelected] = useSyncState<string | undefined>(undefined);

	const [selectOptions, setSelectOptions] = useState<SelectOption[]>([]);

	useEffect(() => {
		console.log('filterFormDetail:');
		setSelectOptions(filterFormDetail(formData) as any);
	}, [formData, clentId]);

	return (
		<FillFormContainer>
			<UserRole userRole={userRole}>{userRole}</UserRole>
			<TitleContianer>{t('form-record')}</TitleContianer>
			<CascaderSelect clientId={clentId} list={selectOptions} />
		</FillFormContainer>
	);
};

export default FillForm;
